package cn.dxs.adt.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import butterknife.BindView;
import cn.dxs.adt.R;
import cn.dxs.adt.utils.BitmapUtil;
import cn.dxs.adt.utils.Util;
import cn.dxs.adt.view.CokePoster;

/**
 * 海报制作
 */
public class PosterMakingActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private CokePoster mV_cokePoster;
    private EditText mEt_content;
    private EditText mEt_txtQRcode;
    private EditText mEt_mpName;
    private Button mBtn_preview;
    private Button mBtn_save;
    private Button mBtn_topTmg;
    private Button mBtn_content;
    private Button mBtn_imgQRcode;
    private Button mBtn_txtQRcode;
    private Button mBtn_mpName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_poster_making);
        initToolBar(toolbar, true, getTitle());
        init();
    }

    private void init() {
        initView();
        initData();
    }

    private void initView() {
        mV_cokePoster = findViewById(R.id.v_cokePoster);
        mEt_content = findViewById(R.id.et_content);
        mEt_txtQRcode = findViewById(R.id.et_txtQRcode);
        mEt_mpName = findViewById(R.id.et_mpName);

        mBtn_preview = findViewById(R.id.btn_preview);
        mBtn_save = findViewById(R.id.btn_save);
        mBtn_topTmg = findViewById(R.id.btn_topTmg);
        mBtn_content = findViewById(R.id.btn_content);
        mBtn_imgQRcode = findViewById(R.id.btn_imgQRcode);
        mBtn_txtQRcode = findViewById(R.id.btn_txtQRcode);
        mBtn_mpName = findViewById(R.id.btn_mpName);
        mBtn_preview.setOnClickListener(this);
        mBtn_save.setOnClickListener(this);
        mBtn_topTmg.setOnClickListener(this);
        mBtn_content.setOnClickListener(this);
        mBtn_imgQRcode.setOnClickListener(this);
        mBtn_txtQRcode.setOnClickListener(this);
        mBtn_mpName.setOnClickListener(this);
        findViewById(R.id.btn_contentFontSizeAdd).setOnClickListener(this);
        findViewById(R.id.btn_contentFontSizeMinus).setOnClickListener(this);
        findViewById(R.id.btn_contentLineHeightAdd).setOnClickListener(this);
        findViewById(R.id.btn_contentLineHeightMinus).setOnClickListener(this);
        findViewById(R.id.btn_dateAdd).setOnClickListener(this);
        findViewById(R.id.btn_dateMinus).setOnClickListener(this);
    }

    private void initData() {
        mEt_content.setText("别因为一次失败，就放弃你原先所要达到的目的。\nDo not, for one repulse, give up the purpose that you resolved to effect.");
        mEt_txtQRcode.setText("小可乐猪🐷开心的一天^_^🐖！");
        mEt_mpName.setText("🐷小可乐猪🐷");
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_preview:
                preview();
                break;
            case R.id.btn_save:
                save();
                break;
            case R.id.btn_topTmg:
                selectPicture(1);
                break;
            case R.id.btn_content:
                content();
                break;
            case R.id.btn_imgQRcode:
                selectPicture(2);
                break;
            case R.id.btn_txtQRcode:
                txtQRcode();
                break;
            case R.id.btn_mpName:
                mpName();
                break;
            case R.id.btn_contentFontSizeAdd:
                mV_cokePoster.setContentFontSize(1);
                break;
            case R.id.btn_contentFontSizeMinus:
                mV_cokePoster.setContentFontSize(-1);
                break;
            case R.id.btn_contentLineHeightAdd:
                mV_cokePoster.setContentLineHeight(0.1f);
                break;
            case R.id.btn_contentLineHeightMinus:
                mV_cokePoster.setContentLineHeight(-0.1f);
                break;
            case R.id.btn_dateAdd:
                mV_cokePoster.setDate(1);
                break;
            case R.id.btn_dateMinus:
                mV_cokePoster.setDate(-1);
                break;
            default:
                break;
        }
    }

    private void preview() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        Bitmap bitmap = getBitmapFromView(mV_cokePoster);
        ImageView view = new ImageView(this);
        view.setImageBitmap(bitmap);
        builder.setView(view);
        builder.setCancelable(true);
        builder.create().show();
    }

    private void save() {
        Bitmap bitmap = getBitmapFromView(mV_cokePoster);
        if (bitmap == null) return;
        File file = new File(Environment.getExternalStorageDirectory(), "Pictures/Gallery/owner/可乐海报/");
        if (!file.exists()) {
            if (!file.mkdirs()) return;
        }
        File saveFile = new File(file, "cokePoster_" + Util.getCreateTime(new Date(), "yyyyMMdd_HHmmss") + ".png");

        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(saveFile);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.flush();
            showToast("海报已保存到相册，赶紧晒一下吧！");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Bitmap getBitmapFromView(View v) {
        Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.RGB_565);
        Canvas c = new Canvas(b);
        v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
        // Draw background
        Drawable bgDrawable = v.getBackground();
        if (bgDrawable != null)
            bgDrawable.draw(c);
        else
            c.drawColor(Color.WHITE);
        // Draw view to canvas
        v.draw(c);
        return b;
    }

    private void topTmg(String imgPath) {
        mV_cokePoster.setTopImg(BitmapUtil.getRotatedBitmap(imgPath));
    }

    private void content() {
        mEt_content.setVisibility(View.GONE);
        mEt_txtQRcode.setVisibility(View.GONE);
        mEt_mpName.setVisibility(View.GONE);
        showSoftInput(mEt_content);
    }

    private void imgQRcode(String imgPath) {
        mV_cokePoster.setImgQRcode(BitmapFactory.decodeFile(imgPath));
    }

    private void txtQRcode() {
        mEt_content.setVisibility(View.GONE);
        mEt_txtQRcode.setVisibility(View.GONE);
        mEt_mpName.setVisibility(View.GONE);
        showSoftInput(mEt_txtQRcode);
    }

    private void mpName() {
        mEt_content.setVisibility(View.GONE);
        mEt_txtQRcode.setVisibility(View.GONE);
        mEt_mpName.setVisibility(View.GONE);
        showSoftInput(mEt_mpName);
    }

    private void selectPicture(int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data == null) return;
            String imgPath = data.getData().getLastPathSegment();
            if (requestCode == 1) {
                topTmg(imgPath);
            } else if (requestCode == 2) {
                imgQRcode(imgPath);
            }
        } else {

        }
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public void showSoftInput(EditText editText) {
        editText.setVisibility(View.VISIBLE);
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        editText.setSelection(editText.getText().length());
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) imm.showSoftInput(editText, 0);
    }

    public void closeSoftInput(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null)
            imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {//点击editText控件外部
                closeSoftInput(v);
                closeEditView(v);
            }
        }
        //必不可少，否则所有的组件都不会有TouchEvent了
//        return getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);
        return super.dispatchTouchEvent(ev);
    }

    private void closeEditView(View v) {
        v.setVisibility(View.GONE);
        switch (v.getId()) {
            case R.id.et_content:
                mV_cokePoster.setContent(mEt_content.getText().toString());
                break;
            case R.id.et_txtQRcode:
                mV_cokePoster.setTxtQRcode(mEt_txtQRcode.getText().toString());
                break;
            case R.id.et_mpName:
                mV_cokePoster.setMpName(mEt_mpName.getText().toString());
                break;
        }
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }
}